<?php
/**
 * Indice de noticias
 * @author Sahib J. Leo
 */
require '../config.php';
require PATH . 'classes/ofj-orm/Noticia.php';

$css_arr = array(
  'css/noticias/index.css',
  'css/noticias/sidebar.css'
);
if (LANG == 'en') {
  array_push($css_arr, 'css/noticias/sidebar-en.css');
}
require PATH . 'layout/header.php';
$news_old_lang_source = Lang::setSource('noticias');
?>

<section id="news_index">
  <header id="news_header">
    <form id="frm_news_filter" class="clearfix">
      <h1>
        <?php if( LANG == 'es'): ?>
        <span><?php echo Lang::get('news_title') ?></span>
        <?php echo Lang::get('from_ofj') ?>
        <?php else: ?>
        <?php echo Lang::get('from_ofj') ?>
        <span><?php echo Lang::get('news_title') ?></span>
        <?php endif ?>
      </h1>
      <div id="news_btn_rss_wrapper">
        <a href="#" id="news_btn_rss" title="RSS Feed">RSS</a>
      </div>
      <div id="news_search_wrapper" class="clearfix">
        <input type="search" name="search" id="news_search_field"
          maxlength="50m" placeholder="<?php
          echo Lang::get('search_placeholder') ?>" />
        <a href="#" id="news_btn_search"
          title="<?php echo Lang::get('btn_search') ?>"><?php
          echo Lang::get('btn_search') ?></a>
      </div>
      <div id="news_month_selector_wrapper">
        <a href="#" id="news_month_selector"><?php
          if( !isset($_GET['date']) ):
            echo Lang::get('month_filter');
          else:
            list($year, $month) = explode('-', $_GET['date']);
            echo strftime('%B %Y', mktime(0,0,0,$month,1,$year));
          endif;
        ?></a>
        <ul name="news_month_options" id="news_month_options">
          <li><a href="noticias/"><?php echo Lang::get('all_months') ?></a></li>
          <?php
          /*
           * Lista de meses, desde Mayo 2012 hasta la actualidad
           */
          $month = date('n'); // Mes actual
          $year  = date('Y'); // Año actual
          
          // Fecha del mes actual
          $date = mktime(0, 0, 0, $month, 1, $year);

          // Fecha minima, Abril 2012, es decir, solo se muestra hasta Mayo 2012.
          $min_date = mktime(0, 0, 0, 4, 1, 2012);

          while($date > $min_date):
          ?>
          <li><a href="noticias/?date=<?php
            echo date('Y-n', $date)
            ?>"><?php echo strftime('%B %Y', $date) ?></a></li>
          <?php
            // Restar un mes a la fecha actual
            $date = mktime(0, 0, 0, --$month, 1, $year);
          endwhile
          ?>
        </ul>
      </div>
    </form>
  </header>

  <?php
  /*
   * Mostrar detalle de noticia si existe $_GET['id']
   */
  if( isset($_GET['id']) ):
    $noticia_id = (int)$_GET['id'];

    try{
      $Noticia = Noticia::instance()->findById($noticia_id);
    }catch(SahORMException $e){
      die('Ocurrio un error al obtener la noticia ('
        . $e->getSqlError() . ')');
    }

    if(!$Noticia):
    ?>
    <div id="not_found"><?php echo Lang::get('notice_not_found') ?></div>
    <?php
    else:
    ?>
    <article class="newsletter">
      <header class="clearfix">
        <i></i>
        <h3><?php
          echo htmlentities($Noticia->get('titulo'), ENT_QUOTES, 'utf-8')
        ?></h3>
      </header>
      <img src="<?php echo Noticia::getImageUrl($Noticia) ?>"
        align="left"
        class="newsletter_image"
        width="<?php echo Noticia::IMG_WIDTH ?>"
        height="<?php echo Noticia::IMG_HEIGHT ?>" />
      <div class="newsletter_date"><?php
        echo strftime('%B %d, %Y', strtotime($Noticia->fecha))
      ?></div>
      <?php echo $Noticia->get('contenido') ?>
    </article>

    <!-- botones sociales y de navegación -->
    <div id="news_social_buttons" class="clearfix">
      <div id="news_btn_gplus">
        <g:plusone size="small"></g:plusone>
        <div class="g-plus" data-action="share" data-annotation="none" data-height="15"></div>
        <script type="text/javascript">
          <?php if(LANG == 'es'): ?>
          window.___gcfg = {lang: 'es'};
          <?php endif ?>
          (function() {
            var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
            po.src = 'https://apis.google.com/js/plusone.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
          })();
        </script>
      </div>
      <div id="news_btn_facebook">
        <div class="fb-like"
          data-href="<?php echo BASE, 'noticias/?id=', $Noticia->id ?>"
          data-send="true"
          data-width="200"
          data-layout="button_count"
          data-show-faces="false"></div>
        <div id="fb-root"></div>
        <script>(function(d, s, id) {
          var js, fjs = d.getElementsByTagName(s)[0];
          if (d.getElementById(id)) return;
          js = d.createElement(s); js.id = id;
          <?php if(LANG == 'es'): ?>
          js.src = "//connect.facebook.net/es_LA/all.js#xfbml=1";
          <?php else: ?>
          js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
          <?php endif ?>
          fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));</script>
      </div>
      <div id="news_notice_navigation_buttons" class="clearfix">
        <a href="noticias/" id="news_btn_index"
          title="<?php echo Lang::get('back_to_index') ?>"><?php
          echo Lang::get('back_to_index')
        ?></a>
        <?php
        /*
         * Obtener el ID de la noticia anterior
         */
        $arguments = array(':fecha' => $Noticia->fecha);
        try{
          $PrevNotice = Noticia::instance()->findOne(array(
            'where'     => "`publicada`='S' AND `fecha` < :fecha",
            'order_by'  => '`fecha` DESC',
            'arguments' => $arguments
          ));
        } catch(SahORMException $e) {
          die('No se pudo obtener la noticia previa ('
            . $e->getSqlError() . ')');
        }
        if($PrevNotice):
        ?>
        <a href="noticias/?id=<?php echo $PrevNotice->id ?>"
          id="news_btn_prev_notice"
          title="<?php echo Lang::get('prev_notice' ) ?>"><?php
            echo Lang::get('prev_notice' )
        ?></a>
        <?php
        endif;
        /*
         * Obtener el ID de la noticia siguiente
         */
        try{
          $NextNotice = Noticia::instance()->findOne(array(
            'where'     => "`publicada`='S' AND `fecha` > :fecha",
            'order_by'  => '`fecha` ASC',
            'arguments' => $arguments
          ));
        } catch(SahORMException $e) {
          die('No se pudo obtener la noticia previa ('
            . $e->getSqlError() . ')');
        }
        if($NextNotice):
        ?>
        <a href="noticias/?id=<?php echo $NextNotice->id ?>"
          id="news_btn_next_notice"
          title="<?php echo Lang::get('next_notice' ) ?>"><?php
          echo Lang::get('next_notice' )
        ?></a>
        <?php endif ?>
      </div>
    </div>
    <!-- // botones sociales y de navegación -->

    <?php
    /*
     * Definir variables para el script de comentarios
     */
    $comments_type = 'noticia';
    $comments_source_id = $Noticia->id;
    require_once PATH . 'layout/comments.php';
    ?>

    <?php
    endif;
    /* END: if !$Noticia */

  else:
  /*
   * Mostrar la lista de noticias
   */
  ?>

  <!-- Lista de noticias -->
  <section>
    <?php
    /*
     * Cargar la lista de noticias con los filtros adecuados
     */
    $noticias_per_page = 6;
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    
    if($page == 0){
      $page = 1;
    }

    // Generar el WHERE para la seleccion de noticias
    $where = "`publicada` = 'S'";
    $arguments = array();

    // Filtro por mes
    if( isset($_GET['date']) ){
      list($year, $month) = explode('-', $_GET['date']);
      $where .= " AND (YEAR(`fecha`) = :year AND MONTH(`fecha`) = :month)";
      $arguments[':year'] = $year;
      $arguments[':month'] = $month;
    }

    // Filtro por busqueda
    if( isset($_GET['search']) ){
      $where .= " AND (`titulo` LIKE :search OR `titulo_en` LIKE :search)";
      $arguments[':search'] = '%' . $_GET['search'] . '%';
    }

    
    // Calcular el número de paginas
    try{
      $total_pages = ceil( Noticia::instance()->count(array(
        'where'     => $where,
        'arguments' => $arguments
      )) / $noticias_per_page );
    }catch(SahORMException $e){
      die('Ocurrio un error al contar el numero de noticias. ('
        . $e->getSqlError() . ')');
    }

    // Obtener la lista de noticias
    try{
      $noticias = Noticia::instance()->find(array(
        'order_by'  => '`id` DESC',
        'limit'     => $noticias_per_page,
        'where'     => $where,
        'arguments' => $arguments,
        'skip'      => ($page - 1) * $noticias_per_page,
      ));
    }catch(SahORMException $e){
      die('Ocurrio un error al obtener la lista de noticias. ('
        . $e->getSqlError() . ')');
    }

    if(count($noticias) == 0):
    ?>
    <div id="not_found"><?php echo Lang::get('news_not_found') ?></div>
    <?php
    else:
    foreach($noticias as $Noticia):
    ?>
    <article class="news_article clearfix">
      <div class="news_article_image_wrapper">
        <img src="<?php echo Noticia::getImageUrl($Noticia) ?>"
          width="<?php echo Noticia::IMG_WIDTH ?>"
          height="<?php echo Noticia::IMG_HEIGHT ?>"/>
      </div>
      <div class="news_article_description_wrapper">
        <header class="clearfix">
          <i class="news_notice_title_arrow"></i>
          <h3 class="news_notice_title"><?php
            echo htmlentities($Noticia->get('titulo'), ENT_QUOTES, 'utf-8')
          ?></h3>
        </header>
        <div class="news_notice_date">
          <?php echo strftime('%B %d, %Y', strtotime($Noticia->fecha)) ?>
        </div>
        <div class="news_notice_summary">
          <?php echo $Noticia->getSummary(25), ' ...' ?>
        </div>
        <div class="news_read_more_wrapper">
          <a href="noticias/?id=<?php echo $Noticia->id ?>"><img
            src="img/home/see-details.gif" width="14" height="17"
            valign="middle" /> <?php
            echo Lang::get('read_more') ?></a>
        </div>
      </div>
    </article>
    <?php
    endforeach;
    endif;
    /* END: if count $noticias = 0 */
    ?>
  </section>
  <!-- // Lista de noticias -->
  <?php
  /*
   * Paginado
   */
  if($total_pages > 1):
    $prev_url = 'javascript:;';
    $next_url = 'javascript:;';
    $date     = null;
    $search   = null;
    
    // Agregar variable "date" al query string
    if(isset($_GET['date'])){
      $date = '&date=' . $_GET['date'];
    }

    // Agregar variable "search" al query string
    if(isset($_GET['search'])){
      $search = '&search=' . urlencode($_GET['search']);
    }

    if($page > 1){
      $prev_url = 'noticias/?page=' . ($page - 1) . $date . $search;
    }

    if($page < $total_pages){
      $next_url = 'noticias/?page=' . ($page + 1) . $date . $search;
    }
  ?>
  <div class="clearfix">
    <div class="pagination_numbers clearfix">
      <?php for($i = 1; $i <= $total_pages; $i++): ?>
      <a href="<?php
        if($page == $i):
          echo 'javascript:;';
        else:
          echo 'noticias/?page=', $i, $date, $search;
        endif;
      ?>" <?php
        if($page == $i):
          echo 'class="active"';
        endif;
      ?>><?php echo $i ?></a>
      <?php endfor ?>
    </div>
    <div class="pagination_buttons clearfix">
      <a href="<?php echo $prev_url ?>" class="pagination_prev">&nbsp;</a>
      <a href="<?php echo $next_url ?>" class="pagination_next">&nbsp;</a>
    </div>
  </div>
  <?php
  endif;
  /* END: if($total_pages > 1) */

  endif;
  /* END: if( isset($_GET['id']) ) */
  ?>
</section>
<!-- // noticias index -->

<?php require PATH . 'noticias/aside.php'; ?>

<?php
Lang::setSource($news_old_lang_source);

if( ! isset($js_arr) ){ $js_arr = array(); }
$js_arr[] = 'js/noticias/noticias.js';

require PATH . 'layout/footer.php';
?>